package com.xiaochong.tir.api.webws;

import javax.websocket.Session;

import com.xc.logclient.utils.LogTrace;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @Project : xc-tir
 * @Package Name : com.xiaochong.tir.api.webws
 * @Description : TODO WS连接管理容器
 * @Author : daizhiqing@xiaochong.com
 * @Creation Date : 2018年05月28日下午7:56
 * @ModificationHistory Who When What
 */
public class WsSessionContainer {

    private static ConcurrentHashMap<String, Session> sessionMap = new ConcurrentHashMap<>();

    public static ConcurrentHashMap<String, Session> getSessionMap() {
        return sessionMap;
    }


    public static void addSession(Session session,int exchangeId,int transactionId){
        if(session != null){
            sessionMap.put(session.getId()+exchangeId+transactionId, session);
        }
    }

    public static Session removeSession(Session session,int exchangeId,int transactionName){
        if(session != null){
            return sessionMap.remove(session.getId()+exchangeId+transactionName);
        }
        return null;
    }

    /**
     * 群发
     * @param msg
     * @return
     */
    public static int sendAllMsg(String msg ,int exchangeId,int transactionId){
        LogTrace.info("sendAllMsg","key",exchangeId+transactionId+"");
        int count = 0;
        for (String key: sessionMap.keySet()) {
            if(key.endsWith(exchangeId+transactionId+"")){
                try {
                    synchronized(key) {
                        sessionMap.get(key).getBasicRemote().sendText(msg);
                    }
                }catch (Exception e){
                    e.printStackTrace();
//                    continue;
                }
                count ++;
            }
        }
        return count;
    }

}
